import {getToken, getUserInfo, removeToken, removeUserInfo, setToken, setUserInfo} from '@/utils/auth'
import {getInfoApi, loginApi} from '@/api/auth'
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import {Message} from 'element-ui'

Vue.use(Vuex)

export default new Vuex.Store({
    // 定义数据
    state: {
        token: getToken() || '',
        userInfo: getUserInfo() || {}
    },
    // 定义计算属性
    getters: {
        username: state => state.userInfo.username || '',
        identity: state => state.userInfo.identity || ''
    },
    // 定义修改操作
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            setToken(token)
        },
        SET_USER_INFO(state, user) {
            setUserInfo(user)
            state.userInfo = user
        },
        RESET_STATE(state) {
            removeToken()
            removeUserInfo()
            state.token = ''
            state.userInfo = {}
        }
    },
    // 定义逻辑操作
    actions: {
        // 登录操作
        async login({commit, dispatch, getters}, info) {
            // // 1. 发起请求
            const {data} = await loginApi(info)
            // // 2. 存储token
            commit('SET_TOKEN', data.token)
            commit('SET_USER_INFO', data.user)
            await router.push(getters.identity == 'user' ? '/classification' : '/')
            Message.success('登录成功')
        },
        async getUserInfo({commit}) {
            const {data} = await getInfoApi()
            commit('SET_USER_INFO', data)
        }
    }
})
